package HighConcurrency.JUC;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinPoolDemo {//分叉和行池
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool p=new ForkJoinPool();
        ForkJoinTask<Long> t=p.submit(new Sum(1, 10000000000L));
        System.out.println(t.get());
        p.shutdown();
        //非常有效的提高CPU的利用率，一般凌晨使用
        //在数据量小的情况下，循环性能更好，但是数据量大的情况下，分叉和行池性能更好
        //在分叉合并中当某一个核将所有任务完成后，会从其他核任务队列末尾取任务执行，
        // 这叫work stealing策略

    }
}
class Sum extends RecursiveTask<Long> {
    long start, end;

    Sum(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start <= 10000) {
            long sum = 0;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
//            System.out.println("compute" + sum);
            return sum;
        }else {
            long middle = (start + end) / 2;
            Sum left = new Sum(start, middle);
            left.fork();
            Sum right = new Sum(middle + 1, end);
            right.fork();
//            System.out.println("fork");
            return left.join() + right.join();
        }
    }
}